package com.health.ts.service.attachment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.ts.dao.attachment.AttachmentMapper;
import com.health.ts.entity.attachment.Attachment;
import com.health.ts.utils.AssertUtil;
import com.health.ts.utils.FileUtil;
import com.health.ts.utils.GenerateIdUtil;

/**
 * <p>
 * 会诊附件表 服务实现类
 * </p>
 * 
 * @author ${author}
 * @since 2017-06-13
 */
@Service
public class AttachmentService extends ServiceImpl<AttachmentMapper, Attachment> {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	@Value("${ts.upload.dir}")
	private String uploadBaseDir;// 保存根路径
	
	@Value("${ts.agreebook.dir}")
	private String agreeBookDir;// 患者知情同意书路径

	/**
	 * 附件上传
	 * @param business_id
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public void upload(String business_id, List<MultipartFile> files) throws Exception {
		AssertUtil.notEmpty(files, "上传文件为空");
		// 存储在磁盘上的路径(不包括文件名)
		String saveBasePath = uploadBaseDir + File.separator + business_id;
		FileUtil.newFolder(saveBasePath);
		Attachment attechment = null;
		List<Attachment> attachs = new ArrayList<Attachment>();
		for (MultipartFile file : files) {
			// 获取文件名
			File tempFile = new File(file.getOriginalFilename());
			String fileName = tempFile.getName();
			// 存储在磁盘上的路径(包括文件名)
			String savePath = saveBasePath + File.separator + fileName;
			// 存储在数据库上的路径
			String saveDbPath = File.separator + business_id + File.separator + fileName;
			File dest = new File(savePath);
			// 写入文件
			file.transferTo(dest);
			// 记录附件表信息
			attechment = new Attachment();
			attechment.setId(GenerateIdUtil.makeID());
			attechment.setBusiness_id(business_id);// 设置业务id
			attechment.setFilename(fileName);
			attechment.setFilepath(saveDbPath);
			attechment.setCreate_time(new Date());
			attachs.add(attechment);
		}
		// 保存附件信息到数据库中
		saveAttachmentToDb(business_id, attachs);
	}

	/**
	 * 保存附件信息到数据库中
	 * 
	 * @param business_id
	 * @param attachs
	 */
	@Transactional
	public void saveAttachmentToDb(String business_id, List<Attachment> attachs) {
		// 删除原有数据
//		Wrapper<Attachment> deleteAttachWrapper = new EntityWrapper<Attachment>();
//		deleteAttachWrapper.eq("business_id", business_id);
//		this.delete(deleteAttachWrapper);
		//批量写入附件信息到数据库中
		this.saveBatch(attachs);
	}
	
	/**
	 * 根据业务ID获取附件列表
	 * @param business_id
	 * @return
	 */
	public List<Attachment> listAttachments(String business_id){
		//附件列表
		QueryWrapper<Attachment> attachWrapper = new QueryWrapper<Attachment>();
		attachWrapper.eq("business_id", business_id);
		return this.list(attachWrapper);
	}
	
	/**
	 * 根据附件ID删除附件
	 * @param business_id
	 * @return
	 */
	public void deleteAttachment(String attachId){
		Attachment attachment = this.baseMapper.selectById(attachId);
		if(attachment!=null){
			//删除文件
			FileUtil.deleteFile(uploadBaseDir+attachment.getFilepath());
			//删除DB附件信息
			this.baseMapper.deleteById(attachId);
		}
	}
	
	/**
	 * 根据附件ID获取附件
	 * @param id
	 * @return
	 */
	public Map<String,Object> getAttachment(String attachmentId){
		Map<String,Object> result=new HashMap<String,Object>();
		Attachment attachment = this.baseMapper.selectById(attachmentId);
		if(attachment!=null){
			result.put("fileName", attachment.getFilename());
			
			String filePath =uploadBaseDir+File.separator+ attachment.getFilepath();
			File attachmentFile=new File(filePath);
			byte[] attachBytes=null;
			try {
				attachBytes = FileUtil.readFileToByteArray(attachmentFile);
			} catch (IOException e) {
				log.error("下载文件过程中发生异常： ",e);
				attachBytes= new byte[0];
			}
			result.put("bytes", attachBytes);
		}else{
			result.put("fileName", "unkown");
			result.put("bytes", new byte[0]);
		}
		return result;
	}
	
	/**
	 * 获取患者知情同意书附件
	 * @return
	 */
	public Map<String,Object> getAgreeBook(){
		Map<String,Object> result=new HashMap<String,Object>();
		String filePath =agreeBookDir;
		File agreeBookFile=new File(filePath);
		if(agreeBookFile.exists()){
			result.put("fileName", agreeBookFile.getName());
			byte[] attachBytes=null;
			try {
				attachBytes = FileUtil.readFileToByteArray(agreeBookFile);
			} catch (IOException e) {
				log.error("下载文件过程中发生异常： ",e);
				attachBytes= new byte[0];
			}
			result.put("bytes", attachBytes);
		}else{
			result.put("fileName", "unkown");
			result.put("bytes", new byte[0]);
		}
		return result;
	}

}
